package com.fc.redap.shiro.common;

import com.fc.redap.entity.SessionEntity;
import com.fc.redap.service.ISessionEntityService;
import org.apache.shiro.io.DefaultSerializer;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.Date;

public class SessionDao extends EnterpriseCacheSessionDAO {

    @Autowired
    private ISessionEntityService sessionService;

    private DefaultSerializer<HTSession> serializer = new DefaultSerializer<HTSession>();

    @Override
    protected Serializable doCreate(org.apache.shiro.session.Session session) {
        Serializable sessionId = super.doCreate(session);

        if (isAppSession(session)) {
            HTSession htSession = (HTSession) session;
            SessionEntity sessionEntity = new SessionEntity();
            sessionEntity.setSessionId(sessionId.toString());
            sessionEntity.setSession(serializer.serialize(htSession));
            sessionService.save(sessionEntity);
        }
        return sessionId;
    }

    @Override
    protected org.apache.shiro.session.Session doReadSession(Serializable sessionId) {
        SessionEntity entity = sessionService.getSession(sessionId.toString());
        if(entity != null){
            HTSession session = serializer.deserialize(entity.getSession());
            session.setLastAccessTime(new Date());
            return session;
        }
        return null;
    }

    @Override
    protected void doUpdate(org.apache.shiro.session.Session session) {
        super.doUpdate(session);
        if (session instanceof ValidatingSession && !((ValidatingSession) session).isValid()) {
            return; //如果会话过期/停止 没必要再更新了
        }
        SessionEntity entity = sessionService.getSession(session.getId().toString());
        if (entity != null) {
            entity.setSession(serializer.serialize((HTSession) session));
            sessionService.update(entity);
        }
    }

    @Override
    protected void doDelete(org.apache.shiro.session.Session session) {
        super.doDelete(session);
    }

    private boolean isAppSession(org.apache.shiro.session.Session session) {
        HTSession advSession = (HTSession) session;
        return (advSession.getPlatform() == HTSession.Platform.ios
                || advSession.getPlatform() == HTSession.Platform.android
                || advSession.getPlatform() == HTSession.Platform.wp);
    }
}
